import type { MenuItem } from '@/types/munuType'
import dayjs from 'dayjs'

/**
 * 工具函数封装
 */
export const formatMoney = (num?: string | number) => {
  if (!num) return '0.00'
  const a = parseFloat(num.toString())
  return a.toLocaleString('zh-CN')
}

export const formatDate = (date?: Date, template: string = 'YYYY-MM-DD HH:mm') => {
  let curDate = new Date()
  if (date) curDate = date
  return dayjs(date).format(template)
}

export const getTreeData = (menu: MenuItem[]): string[] => {
  return menu.reduce((result: string[], item: MenuItem) => {
    return result.concat(
      Array.isArray(item.children) && !item.buttons ? getTreeData(item.children) : (item.path as string)
    )
  }, [])
}

export const searchRoute = (pathname: string, routes: any) => {
  for (const item of routes) {
    if (item.path === pathname) {
      return item
    }
    if (item.children) {
      const result = searchRoute(pathname, item.children)
      if (result) return result
    }
  }
  return ''
}

export const formatMobile = (mobile?: string | number) => {
  if (!mobile) return ''
  mobile = mobile.toString()
  return mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
}
